import os
from PIL import Image, ImageEnhance
import glob


def resize_image(input_path, output_path, size=(240, 240)):
    """
    高质量图片缩放与转换，保留动画和图像细节
    """
    try:
        with Image.open(input_path) as img:
            # 检查是否为动态图片
            is_animated = getattr(img, 'is_animated', False)

            if is_animated:
                # 处理动态GIF
                frames = []
                original_durations = []

                for frame in range(img.n_frames):
                    img.seek(frame)
                    current_frame = img.copy().convert('RGBA')

                    # 保存原始帧持续时间
                    original_durations.append(img.info.get('duration', 100))

                    # 计算等比缩放
                    original_width, original_height = current_frame.size
                    ratio = min(size[0] / original_width, size[1] / original_height)
                    new_width = int(original_width * ratio)
                    new_height = int(original_height * ratio)

                    # 高质量缩放
                    resized_frame = current_frame.resize(
                        (new_width, new_height),
                        Image.Resampling.BICUBIC  # 使用BICUBIC插值
                    )

                    # 对比度和锐度增强
                    enhancer = ImageEnhance.Contrast(resized_frame)
                    resized_frame = enhancer.enhance(1.1)

                    enhancer = ImageEnhance.Sharpness(resized_frame)
                    resized_frame = enhancer.enhance(1.2)

                    # 创建背景
                    final_frame = Image.new('RGBA', size, (255, 255, 255, 0))
                    x = (size[0] - new_width) // 2
                    y = (size[1] - new_height) // 2
                    final_frame.paste(resized_frame, (x, y), resized_frame)

                    frames.append(final_frame)

                # 保存动态GIF
                frames[0].save(
                    output_path,
                    save_all=True,
                    append_images=frames[1:],
                    duration=original_durations,
                    loop=0,
                    disposal=2,
                    optimize=True,
                    quality=95,  # 高质量
                    transparent=0
                )
            else:
                # 处理静态图片
                img = img.convert('RGBA')

                # 等比缩放
                original_width, original_height = img.size
                ratio = min(size[0] / original_width, size[1] / original_height)
                new_width = int(original_width * ratio)
                new_height = int(original_height * ratio)

                # 高质量缩放
                resized_img = img.resize(
                    (new_width, new_height),
                    Image.Resampling.BICUBIC
                )

                # 对比度和锐度增强
                enhancer = ImageEnhance.Contrast(resized_img)
                resized_img = enhancer.enhance(1.1)

                enhancer = ImageEnhance.Sharpness(resized_img)
                resized_img = enhancer.enhance(1.2)

                # 创建背景
                final_img = Image.new('RGBA', size, (255, 255, 255, 0))
                x = (size[0] - new_width) // 2
                y = (size[1] - new_height) // 2
                final_img.paste(resized_img, (x, y), resized_img)

                final_img.save(
                    output_path,
                    format='GIF',
                    optimize=True,
                    quality=95,
                    transparent=0
                )

        print(f"已保存: {output_path}")
    except Exception as e:
        print(f"处理图片时出错 {input_path}: {str(e)}")


def process_directory(input_dir, output_dir):
    """
    批量处理图片目录
    """
    os.makedirs(output_dir, exist_ok=True)

    image_patterns = ["*.gif", "*.png", "*.jpg", "*.jpeg", "*.bmp", "*.webp"]
    image_files = []
    for pattern in image_patterns:
        image_files.extend(glob.glob(os.path.join(input_dir, pattern)))
        image_files.extend(glob.glob(os.path.join(input_dir, pattern.upper())))

    for image_file in image_files:
        filename = os.path.splitext(os.path.basename(image_file))[0] + '.gif'
        output_path = os.path.join(output_dir, filename)

        print(f"处理: {os.path.basename(image_file)} -> {filename}")
        resize_image(image_file, output_path)

    print(f"完成! 处理了 {len(image_files)} 个文件")


# 使用示例
if __name__ == "__main__":
    input_directory = r"D:\dev\pycharm-codespace\pythonProject2\微信表情包导出\gui版本\微信_gif导出_1"
    output_directory = "./result"
    process_directory(input_directory, output_directory)